import express from 'express';
import fetch from 'node-fetch';
import { getApiKey, getDefaultModel, getUpstreamBaseUrl } from '../config.js';

const router = express.Router();

router.post('/', async (req, res) => {
  const { messages, model, temperature } = req.body || {};
  if (!Array.isArray(messages) || messages.length === 0) {
    return res.status(400).json({ error: 'messages 必须是非空数组' });
  }

  const apiKey = getApiKey();
  if (!apiKey) {
    return res.status(400).json({ error: '后端未配置上游 API Key，请先在设置中配置' });
  }

  const upstreamBase = getUpstreamBaseUrl();
  const useModel = model || getDefaultModel();

  try {
    const resp = await fetch(`${upstreamBase}/v1/chat/completions`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${apiKey}`,
      },
      body: JSON.stringify({
        model: useModel,
        messages,
        temperature: typeof temperature === 'number' ? temperature : 0.7,
        stream: false,
      }),
    });

    if (!resp.ok) {
      const text = await resp.text();
      return res.status(resp.status).json({ error: '上游返回错误', detail: text });
    }

    const data = await resp.json();
    const reply = data?.choices?.[0]?.message?.content || '';
    return res.json({ reply, raw: data });
  } catch (err) {
    return res.status(500).json({ error: '代理请求失败', detail: String(err) });
  }
});

export default router;





